<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			*{
				margin:0;
				padding:0;
			}
			#box{
				height:100px;
				width:100px;
				background-color: orange;
				position: fixed;
				left:0;
				top:0;
			}
			
			#boxtwo{
				height:200px;
				width:200px;
				background-color: red;
				position: fixed;
				left:0;
				top:150px;
			}
		</style>
	</head>
	<body>
		<div id="box"></div>
		<div id="boxtwo"></div>
		<script>
			//核心 this--->box/boxtwo
			let box=document.getElementById("box");
			let boxtwo=document.getElementById("boxtwo");
			let html=document.documentElement||document.body;
			
			function down(e){
				//console.log(this);
				//初始坐标---保存在各自的小盒子身上
				this.beginX=e.offsetX;
				this.beginY=e.offsetY;
				
				//两个小盒子有各自的抬起和移动
				this._move=move.bind(this);
				window.addEventListener("mousemove",this._move);
				
				this._up=up.bind(this);
				window.addEventListener("mouseup",this._up);
			}
			
			function move(e){
				//this应该修改为 box boxtwo
				//console.log(this);//默认 this-->window
				this.endX=e.clientX;
				this.endY=e.clientY;
				
				//最大宽度，最大高度
				this.maxW=html.clientWidth-this.offsetWidth;
				this.maxH=html.clientHeight-this.offsetHeight;
				
				let resultX=this.endX-this.beginX;
				let resultY=this.endY-this.beginY;
				
				//范围
				resultX=resultX>this.maxW?this.maxW:(resultX<=0?0:resultX);
				resultY=resultY>this.maxH?this.maxH:(resultY<=0?0:resultY);
				
				this.style.left=resultX+"px";
				this.style.top=resultY+"px";
			}
			
			function up(){
				//console.log(this);
				window.removeEventListener("mousemove",this._move);
				window.removeEventListener("mouseup",this._up);
			}
			
			
			box.addEventListener("mousedown",down);
			boxtwo.addEventListener("mousedown",down);
			
			
		</script>
	</body>
</html>
